package com.loong.user.handler;

import com.loong.common.domain.BaseQuery;
import com.loong.common.domain.Pager;
import com.loong.common.enumerate.ResultCode;
import com.loong.common.exception.GlobalException;
import com.loong.common.utils.TransformUtils;
import com.loong.user.business.ManageResourceBusiness;
import com.loong.user.business.ManageResourceGroupBusiness;
import com.loong.user.common.backend.param.ManageResourceGroupParam;
import com.loong.user.common.backend.param.ManageResourceGroupQueryParam;
import com.loong.user.common.backend.result.ManageResourceGroupResult;
import com.loong.user.model.ManageResource;
import com.loong.user.model.ManageResourceGroup;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: 后台系统资源分组服务
 * @Author: hzp
 * @Date: 2020-10-16 16:33
 */
@Component
public class ManageResourceGroupHandler {
    @Resource
    private ManageResourceGroupBusiness manageResourceGroupBusiness;
    @Resource
    private ManageResourceBusiness manageResourceBusiness;
    @Resource
    private ManageResourceGroupHandler manageResourceGroupHandler;

    /**
     * 保存后台系统资源分组
     * @param param
     */
    public void save(ManageResourceGroupParam param){
        manageResourceGroupBusiness.save(TransformUtils.transform(param, ManageResourceGroup.class));
    }

    /**
     * 更新后台系统资源分组
     * @param param
     */
    public void update(ManageResourceGroupParam param){
        manageResourceGroupBusiness.updateByPrimaryKeySelective(TransformUtils.transform(param, ManageResourceGroup.class));
    }

    /**
     *根据id后台系统资源分组 (这里没做组下面有资源不能删除的控制 后续加上)
     * @param id
     */
    public void deleteById(Long id){
        boolean existsResource = manageResourceGroupHandler.isExistsResource(id);
        //check resource
        if(existsResource)  throw new GlobalException(ResultCode.EXISTS_RESOURCE) ;

        manageResourceGroupBusiness.deleteById(id);

    }

    /**
     * 判断该组下面是否有资源
     * @param id
     * @return
     */
    public boolean isExistsResource(Long id){

        List<ManageResource> resources = manageResourceBusiness.findAllBy("groupId", id);
        if(ObjectUtils.isNotEmpty(resources)){
            return true;
        }
        return false;
    }

    /**
     * 分页查询
     * @param baseQuery
     * @param param
     * @return
     */
    public Pager<ManageResourceGroupResult> pageQuery(BaseQuery baseQuery, ManageResourceGroupQueryParam param){
        Pager<ManageResourceGroup> manageApisPager = manageResourceGroupBusiness.pageQuery(baseQuery, () -> manageResourceGroupBusiness.query(param));
        return TransformUtils.transformPage(manageApisPager, ManageResourceGroupResult.class);
    }
}
